package com.example.authclient.config;

import com.example.util.utils.DfUtils;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.provider.ClientDetailsService;

@Slf4j
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Order(102)
public class WebsecuityImp extends WebSecurityConfigurerAdapter {
  private   static final  Logger logger = LoggerFactory.getLogger(WebsecuityImp.class);


/*    @Override
    public void configure(WebSecurity web) throws Exception {
        super.configure(web);
    }*/
    @Autowired
    private LoginSuccessHandler loginSuccessHandler;
    @Autowired
    private LoginFailHandler loginFailHandler;

    /**
     * security 登录安全认证 配置 在此处
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        logger.info("security安全认证加载");
//        http.
       /* http
                // .requestMatchers().antMatchers 需要忽略认证
                .requestMatchers().antMatchers("/login","/index")
                .and()
                // authorizeRequests().anyRequest().permitAll() 其他的需要校验token
                .authorizeRequests()
                .anyRequest()
//                .antMatchers("/login","/index")
                .permitAll()//校验token
//                .anyRequest().
//                authenticated()
//                .antMatchers("/*","/**")
//                .permitAll()
                .and().formLogin()
                //默认登录跳转
                .loginPage("/login")
                //成功后 处理器
                .successHandler(loginSuccessHandler)
                //失败后处理器
                .failureHandler(loginFailHandler);*/


      /*  http
              //  .requestMatchers().antMatchers("/login","/index") 配置绕过 登录验证 "/login","/index"
                .requestMatchers().antMatchers("/login","/index")
                .and()
                .anonymous().disable()
                .authorizeRequests()
                .antMatchers("/oauth/token").permitAll();*/

        http.authorizeRequests()
                .antMatchers( DfUtils.arrayList(whiteList,resourceList)).permitAll() // 放开权限的url
                .anyRequest().authenticated()
//                .and()
//                .httpBasic().and()//开启httpbasic 基础拦截
//                .csrf().disable()
//                .formLogin()
                //默认登录跳转
//                .loginPage("/login")
//                .successForwardUrl("/index")
                //成功后 处理器
//                .successHandler(loginSuccessHandler)
                //失败后处理器
//                .failureHandler(loginFailHandler);
        ;
    }

    @Value("#{'${myapp.whiteList}'.split(',')}")
    private String[] whiteList;
    @Value("#{'${myapp.resourceList}'.split(',')}")
    private String[] resourceList;


    @Autowired
    private ClientDetailsService clientDetailsService;
//    @Autowired
//    private UserDetailsService userDetailsService;

    @Autowired
    private RedisConnectionFactory redisConnection;

//    @Bean
//    public MyUserDetailsService myUserDetailsService(){
//        return new MyUserDetailsService();
//    }
    @Autowired
    public UserDetailsService userDetailsService;
    @Autowired
    private PasswordEncoder passwordEncoder;
//    @Bean
//    public PasswordEncoder passwordEncoder(){
//        return new MyPasswordEncoder();
//    }

    @Autowired
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder);
//        super.configure(auth);
    }

    /*@Autowired
    public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(daoAuthenticationProvider());
 *//*       auth
                .userDetailsService(myUserDetailsService())
                .passwordEncoder( new BCryptPasswordEncoder(6))*//*
        ;
    }*/
   /* @Bean
    public DaoAuthenticationProvider daoAuthenticationProvider(){
        DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
        // 设置userDetailsService
        provider.setUserDetailsService(myUserDetailsService());
        // 禁止隐藏用户未找到异常
        provider.setHideUserNotFoundExceptions(false);

        // 使用BCrypt进行密码的hash
        provider.setPasswordEncoder( passwordEncoder());
        return provider;
    }
*/
/*    @Bean
    public PasswordEncoder passwordEncoder() {
        return new MyPasswordEncoder();
    }*/
    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }


   /* @Bean
    public TokenStore tokenStore() {
        return new RedisTokenStore(redisConnection);
    }

    @Bean
    @Autowired
    public TokenStoreUserApprovalHandler userApprovalHandler(TokenStore tokenStore){
        TokenStoreUserApprovalHandler handler = new TokenStoreUserApprovalHandler();
        handler.setTokenStore(tokenStore);
        handler.setRequestFactory(new DefaultOAuth2RequestFactory(clientDetailsService));
        handler.setClientDetailsService(clientDetailsService);
        return handler;
    }

    @Bean
    @Autowired
    public ApprovalStore approvalStore(TokenStore tokenStore) throws Exception {
        TokenApprovalStore store = new TokenApprovalStore();
        store.setTokenStore(tokenStore);
        return store;
    }*/

    /**
     * 默认配置 不拦截的资源配置
     * @param web
     * @throws Exception
     */
    @Override
    public void configure(WebSecurity web) throws Exception {
        logger.info("security不拦截静态资源配置加载");
        web.ignoring().antMatchers(resourceList);
        logger.info("security不拦截静态资源配置加载 ："+resourceList.toString());
//        super.configure(web);
    }
}
